<template>
  <!-- <el-menu
    :default-active="activeIndex2"
    class="el-menu-demo"
    mode="horizontal"
    @select="handleSelect"
    background-color="#545c64"
    text-color="#fff"
    active-text-color="#ffd04b"
  >
  <h2 id="mnavh" @click="openHead()">
        <span class="navicon"></span>
      </h2>
    <el-menu-item index="1"><router-link to="/">首页</router-link></el-menu-item>
    <el-menu-item index="2"><router-link to="/about">关于我</router-link></el-menu-item>
    <el-menu-item index="3"><router-link to="/sort">归档</router-link></el-menu-item>
    <el-menu-item index="4">分类</el-menu-item>
    <el-menu-item index="5">标签</el-menu-item>
    <el-menu-item index="6">留言板</el-menu-item>
    <div class="loginbox">
      <el-button type="success" v-if="!isLogin" @click="open(false)">注册</el-button>
      <el-button type="primary" v-if="!isLogin" @click="open(true)">登录</el-button>
      <el-dropdown v-if="isLogin" @command="handleCommand" class="userInfoAvatar">
        <span class="el-dropdown-link">
          <img src="../../static/img/defaultAvatar.png" />
        </span>

        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="goUserInfo" v-show="isLogin">个人中心</el-dropdown-item>
          <el-dropdown-item command="goUserInfo" v-if="isAdmin"><router-link :to="{path:'/writearticle'}">发表文章</router-link></el-dropdown-item>
          <el-dropdown-item command="logout" v-show="isLogin" @click.native="loginOut()">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

   
  </el-menu>-->
  <nav>
    <div class="logo">
      <router-link to="/">
        <a href="javascript:void(0);">Meng's Blog</a>
      </router-link>
    </div>

    <h2 id="mnavh" @click="openHead()">
      <span class="navicon"></span>
    </h2>

    <ul id="starlist" :style="showHead?'display: block':''">
      <li>
        <router-link to="/">
          <a
            href="javascript:void(0);"
            :class="[saveTitle == '/' ? 'title' : '']"
          >{{$t('message.index')}}</a>
        </router-link>
      </li>

      <li>
        <router-link to="/about">
          <a
            href="javascript:void(0);"
            :class="[saveTitle == '/about' ? 'title' : '']"
          >{{$t('message.about')}}</a>
        </router-link>
      </li>

      <li>
        <router-link to="/sort">
          <a
            href="javascript:void(0);"
            :class="[saveTitle == '/sort' ? 'title' : '']"
          >{{$t('message.archive')}}</a>
        </router-link>
      </li>
    </ul>

    <el-dropdown class="select" @command="internation">
      <span class="el-dropdown-link">
        国际化
        <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="zh">中文</el-dropdown-item>
        <el-dropdown-item command="en">English</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <el-dropdown class="userInfoAvatar">
      <span class="el-dropdown-link">
        <img v-if="isLogin" src="../../static/img/touxiang.jpg" />
        <img v-else src="../../static/img/defaultAvatar.png" />
      </span>

      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="goUserInfo" v-show="!isLogin" @click.native="open(false)">注册</el-dropdown-item>
        <el-dropdown-item command="goUserInfo" v-if="!isLogin" @click.native="open(true)">登录</el-dropdown-item>
        <el-dropdown-item command="goUserInfo" v-show="isLogin">个人中心</el-dropdown-item>
        <el-dropdown-item command="goUserInfo" v-if="isAdmin&&isLogin">
          <router-link :to="{path:'/writearticle'}">发表文章</router-link>
        </el-dropdown-item>
        <el-dropdown-item command="logout" v-show="isLogin" @click.native="loginOut()">退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <el-dialog
      :title="boxTitle"
      :visible.sync="dialogFormVisible"
      width="40%"
      :append-to-body="appendToBody"
    >
      <el-form v-if="loginOrRegister" :model="loginForm" ref="loginForm" :rules="loginRules">
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="loginForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input type="password" v-model="loginForm.password" autocomplete="off" show-password></el-input>
        </el-form-item>
      </el-form>

      <el-form v-else :model="registerForm" ref="registerForm" :rules="registerRules">
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="registerForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth" prop="nickName">
          <el-input v-model="registerForm.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input
            type="password"
            v-model="registerForm.password"
            autocomplete="off"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="检查密码" :label-width="formLabelWidth" prop="checkPassword">
          <el-input
            type="password"
            v-model="registerForm.checkPassword"
            autocomplete="off"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm()">确定</el-button>
      </div>
    </el-dialog>

    <el-drawer
      :visible.sync="drawer"
      :direction="direction"
      :append-to-body="appendToBody"
      :with-header="false"
    >
      <ul id="starlist" style="display: block;">
        <li>
          <router-link to="/">
            <a href="javascript:void(0);" :class="[saveTitle == '/' ? 'title' : '']">首页</a>
          </router-link>
        </li>

        <li>
          <router-link to="/about">
            <a href="javascript:void(0);" :class="[saveTitle == '/about' ? 'title' : '']">关于我</a>
          </router-link>
        </li>

        <li>
          <router-link to="/sort">
            <a href="javascript:void(0);" :class="[saveTitle == '/sort' ? 'title' : '']">归档</a>
          </router-link>
        </li>
      </ul>
    </el-drawer>
  </nav>
</template>

<script>
export default {
  data() {
    return {
      drawer: false,
      direction: "ltr",
      showHead: false,
      activeIndex: "1",
      appendToBody: true,
      activeIndex2: "1",
      saveTitle: "",
      isLogin: false,
      isAdmin: false,
      dialogFormVisible: false,
      loginOrRegister: true,
      boxTitle: "登录",
      loginForm: {
        email: "",
        password: ""
      },
      registerForm: {
        email: "",
        password: "",
        checkPassword: "",
        nickName: ""
      },
      loginRules: {
        password: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入密码"));
              } else if (value.length < 6 || value.length > 16) {
                callback(new Error("请确保密码长度6-16位"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入邮箱"));
              } else if (
                !/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/.test(
                  value
                )
              ) {
                callback(new Error("请输入正确的邮箱"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      registerRules: {
        password: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入密码"));
              } else if (value.length < 6 || value.length > 16) {
                callback(new Error("请确保密码长度6-16位"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入邮箱"));
              } else if (
                !/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/.test(
                  value
                )
              ) {
                callback(new Error("请输入正确的邮箱"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        nickName: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入昵称"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        checkPassword: [
          { require: true, message: "密码不可以为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请再次输入密码"));
              } else if (value !== this.registerForm.password) {
                callback(new Error("两次输入密码不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      formLabelWidth: "120px"
    };
  },
  methods: {
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    handleCommand(command) {},
    open(loginOrRegister) {
      this.dialogFormVisible = true;
      this.loginOrRegister = loginOrRegister;
      if (loginOrRegister) {
        this.boxTitle = "登录";
      }
    },
    openHead() {
      this.drawer = true;
    },
    submitForm() {
      if (this.loginOrRegister) {
        this.login("loginForm");
        //  this.$options.methods.login("loginForm");
      } else {
        // this.$options.methods.register("registerForm")
        this.register("registerForm");
      }
    },
    login(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let session = window.localStorage;
          let users = JSON.parse(session.getItem("users"));
          let flag = false;
          for (let i = 0; i < users.length; i++) {
            if (
              this.loginForm.email == users[i].email &&
              this.loginForm.password == users[i].password
            ) {
              if (this.loginForm.email == "1335189318@qq.com") {
                this.isAdmin = true;
              }
              this.isLogin = true;
              session.setItem("login", JSON.stringify(users[i]));
              this.$message.success("登录成功");
              this.dialogFormVisible = false;
              flag = true;
              break;
            }
          }
          if (!flag) {
            this.$message.error("邮箱不存在或者密码不正确");
          }
        } else {
          this.$message.error("请正确填写信息");
          return false;
        }
      });
    },
    register(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let session = window.localStorage;
          let users = JSON.parse(session.getItem("users"));
          let uid = 1;
          if (users == null) {
            users = [];
          } else {
            uid = parseInt(users[users.length - 1].uid) + 1;
          }
          for (let i = 0; i < users.length; i++) {
            if (this.registerForm.email == users[i].email) {
              this.$message.error("该邮箱已被注册");
              return;
            }
            if (this.registerForm.nickName == users[i].nickName) {
              this.$message.error("该昵称已被使用");
              return;
            }
          }
          users.push({
            uid,
            email: this.registerForm.email,
            password: this.registerForm.password,
            nickName: this.registerForm.nickName
          });
          session.setItem("users", JSON.stringify(users));
          this.$message.success("注册成功");
          this.dialogFormVisible = false;
        } else {
          let session = window.localStorage;
          return false;
        }
      });
    },
    loginOut() {
      let session = window.localStorage;
      this.isLogin = false;
      this.isAdmin = false;
      session.removeItem("login");
    },
    internation(command) {
      console.log(command)
      this.$i18n.locale = command;
      localStorage.setItem("lang", command);
    }
  },
  created() {
    let session = window.localStorage;
    let login = JSON.parse(session.getItem("login"));
    if (login != null) {
      this.login = login;
      this.isLogin = true;
      if (login.email == "1335189318@qq.com") {
        this.isAdmin = true;
      }
    }
    let path = window.location.href;
    let index = path.indexOf("#");
    this.saveTitle = path.substring(index + 1, path.length);
  },
  watch: {
    $route(to, form) {
      let path = window.location.href;
      let index = path.indexOf("#");
      this.saveTitle = path.substring(index + 1, path.length);
    }
  }
};
</script>

<style>
.el-tag {
  height: 25px;
  line-height: 25px;
  margin-left: 6px;
}
#starlist li .title {
  color: #00a7eb;
}
.userInfoAvatar {
  width: 35px;
  height: 35px;
  position: absolute;
  right: 0;
  top: 15px;
}

.userInfoAvatar img {
  width: 35px;
  height: 35px;
  border-radius: 50%;
}
.userInfoAvatar img {
  width: 35px;
  height: 35px;
  border-radius: 50%;
}
.loginbox {
  position: absolute;
  right: 0;
  top: 10px;
}
.loginbox button {
  position: relative;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
@media only screen and (max-width:479px){
  .select{
    display: none;
  }
}
.select {
  position: absolute;
  right: 50px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
